<template>
  <div class="login-wrap">
    <h1>注册您的账号</h1>
    <a-form
      ref="refForm"
      class="form"
      :model="form"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :rules="rules"
    >
      <a-form-item label="用户名" name="name">
        <a-input v-model:value.trim="form.name" placeholder="请输入你的用户名" allow-clear />
      </a-form-item>
      <a-form-item label="密码" name="password">
        <a-input
          v-model:value.trim="form.password"
          type="password"
          placeholder="请输入你的密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="确认密码" name="confirmPassword">
        <a-input
          v-model:value.trim="form.confirmPassword"
          type="password"
          placeholder="确认你的密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 18, offset: 6 }">
        <a-button type="primary" @click="handleSubmit()">创建账户</a-button>
        <a-button @click="handleLogin()">返回登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref } from "vue";
  import { rulesRegistry, RegistryDTO } from "./option";
  import router from "/@/router";
  import { showErr, encryptStrByObj } from "/@/util/util";
  import { userRegister } from "/@/api/user/user";
  import { message } from "ant-design-vue";
  export default defineComponent({
    setup() {
      const form = reactive(new RegistryDTO());
      const refForm = ref();
      const handleSubmit = async () => {
        try {
          const validFrorm = await refForm.value.validate();
          const dto = encryptStrByObj(validFrorm, ["password", "confirmPassword"]);
          const { data } = await userRegister(dto);
          if (data) {
            message.success("账号创建成功，自动跳转至登录");
            router.push("/login");
          }
        } catch (err) {
          showErr(err);
        }
      };
      const handleLogin = () => {
        router.push({
          path: "/login",
        });
      };
      const validateConfirmPassword = (_rule: any, value: string) => {
        if (value !== form.password) return Promise.reject("两次密码输入不一致");
        return Promise.resolve();
      };
      const currentRules = {
        confirmPassword: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            validator: validateConfirmPassword,
            trigger: "blur",
          },
        ],
      };
      const rules = {
        ...rulesRegistry,
        ...currentRules,
      };
      return {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
        form,
        rules,
        refForm,
        handleSubmit,
        handleLogin,
      };
    },
  });
</script>
<style lang="scss" scoped>
  .login-wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  .form {
    width: 300px;
  }
</style>
